<template>
	<view>
		<Navbar title="工作台" bgColor="#fff" :hideBtn="true" :h5Show="false"></Navbar>
		<view class="mobile-item-container">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 20rpx 0;">{{user.teamName}}任务</view>
			<u-row gutter="8">
			  <u-col span="6">
			    <view class="item-tj item-tj-frist" @click="remainToFinished">
			      <view style="padding:  4rpx; height: 100%; position: relative;">
			        <view style="display: flex; color: white;">
			          <u-icon name="/static/submit/pending-finished.png" color="#fff" style="margin-left: 8rpx; margin-right: 16rpx;"></u-icon>
			          <text>剩余生产任务</text>
			        </view>
			        <view style="position: absolute; bottom: 48rpx; right: 16rpx;">
			          <u-count-to :startVal="0" :endVal="taskTotal.totalUnFinishedNum" :duration="1000" color="#fff" separator=","></u-count-to>
			        </view>
			      </view>
			    </view>
			  </u-col>
			  <u-col span="6">
			    <view class="item-tj item-tj-second" @click="remainToFinished">
			      <view style="padding: 4rpx; height: 100%; position: relative;">
			        <view style="display: flex; color: white;">
			          <u-icon name="/static/submit/checked-finished.png" color="#fff" style="margin-left: 8rpx; margin-right: 16rpx;"></u-icon>
			          <text>已完成任务</text>
			        </view>
			        <view style="position: absolute; bottom: 48rpx; right: 16rpx;">
			          <u-count-to :startVal="0" :endVal="taskTotal.totalFinishedNum" :duration="1000" color="#fff" separator=","></u-count-to>
			        </view>
			      </view>
			    </view>
			  </u-col>
			  <!-- <u-col span="4">
			    <view class="item-tj item-tj-thrid">
			      <view style="padding: 16rpx; height: 100%; position: relative;">
			        <view style="display: flex; color: white;">
			          <u-icon name="photo" color="#fff"></u-icon>
			          <text>总人数</text>
			        </view>
			        <view style="position: absolute; bottom: 48rpx; right: 16rpx;">
			          <u-count-to :startVal="1" :endVal="1249350" :duration="1500" color="#fff" separator=","></u-count-to>
			        </view>
			      </view>
			    </view>
			  </u-col> -->
			</u-row>
		</view>
		
		<view class="mobile-item-container" v-if="annotationAuth">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 14rpx 0;">批注告警</view>
			<!-- <my-table ></my-table> -->
			<scroll-view @touchstart="touchstart" :scroll-y="true" :scroll-x="true"
				:scroll-top="scrollTop" style="height: 240px;position: relative; -webkit-overflow-scrolling: auto;">
				<uni-table ref="table" border stripe emptyText="暂无更多数据" style="overflow: initial;!important">
					<uni-tr class="tableTh fixed-header" style="background-color: #dbfbdb; position: sticky;top: 0;">
						<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">提交人</uni-th>
						<uni-th align="left" width="90" style="font-size: 12px;color: #62c188;">班组</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">合同号</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">批注类型</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">物料名称</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">物料规格</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">辐射范围</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">异常信息</uni-th>
					</uni-tr>
	
					<uni-tr class="item" v-for="(item, index) in listAr" :key="index">
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.seq }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.createBy}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.teamName}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.otherRelateId}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.annotationTypeDesc}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.bomName}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.bomStandard}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.coverTypeDesc}}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{item.annotationContent}}</uni-td>
					</uni-tr>
	
				</uni-table>
				<view style="height: 20px;"></view>
			</scroll-view>
		</view>
		
		<view class="mobile-item-container">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 40rpx 0;">物料管理</view>
			<u-grid :border="true" col="3">
				<u-grid-item
						@click="gridClick(listItem)"
						v-for="(listItem,listIndex) in materialList"
						:key="listIndex">
					<u-icon color="#2979ff"
							:customStyle="{paddingTop:20+'rpx'}"
							:name="listItem.name"
							:size="22"
					></u-icon>
					<u-badge style="position: absolute; top: 10rpx; right: 30rpx;" 
						type="error" 
						numberType="overflow" 
						max="99" 
						v-model="todo.notice"></u-badge>
					<text class="btn-text">{{listItem.title}}</text>
				</u-grid-item>
			</u-grid>
			<u-toast ref="uToast" />
		</view>
		<Gap />
		
		<view class="mobile-item-container">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 40rpx 0;">生产管理</view>
			<u-grid :border="true" col="3">
				<u-grid-item
						@click="gridClick(listItem)"
						v-for="(listItem,listIndex) in submitReportList"
						:key="listIndex"
						style="padding: 8px;">
					<u-icon color="#2979ff"
							:customStyle="{paddingTop:20+'rpx'}"
							:name="listItem.name"
							:size="24"
					></u-icon>
					<u-badge style="position: absolute; top: 10rpx; right: 30rpx;" 
						type="error" 
						numberType="overflow"
						max="99" 
						v-model="listItem.submitTodo.notice" v-if="listItem.badge"></u-badge>
					<text class="btn-text">{{listItem.title}}</text>
				</u-grid-item>
			</u-grid>
			<u-toast ref="uToast" />
		</view>
		<Gap />
		
		<view class="mobile-item-container">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 40rpx 0;">入库管理</view>
			<u-grid :border="true" col="3">
				<u-grid-item
						@click="gridClick(listItem)"
						v-for="(listItem,listIndex) in stockList"
						:key="listIndex">
					<u-icon color="#2979ff"
							:customStyle="{paddingTop:20+'rpx'}"
							:name="listItem.name"
							:size="22"
					></u-icon>
					<u-badge style="position: absolute; top: 10rpx; right: 30rpx;" 
						type="error" 
						numberType="overflow" 
						max="99" 
						v-model="todo.notice"></u-badge>
					<text class="btn-text">{{listItem.title}}</text>
				</u-grid-item>
			</u-grid>
			<u-toast ref="uToast" />
		</view>
		<Gap />
		
		<view class="mobile-item-container">
		   <view style="font-size: 40rpx; font-weight: bold; padding: 0 0 40rpx 0;">收发货管理</view>
			<u-grid :border="true" col="3">
				<u-grid-item
						@click="gridClick(listItem)"
						v-for="(listItem,listIndex) in waitingHandleList"
						:key="listIndex">
					<u-icon color="#2979ff"
							:customStyle="{paddingTop:20+'rpx'}"
							:name="listItem.name"
							:size="24"
					></u-icon>
					<u-badge style="position: absolute; top: 10rpx; right: 30rpx;" 
						type="error" 
						numberType="overflow" 
						max="99" 
						v-model="todo.notice"></u-badge>
					<text class="grid-text">{{listItem.title}}</text>
				</u-grid-item>
			</u-grid>
			<u-toast ref="uToast" />
		</view>
		<Gap />
		
		<u-toast ref="uToast" />
		<ChangeDept 
			:show="changeDeptShow" 
			:user="user"
			@close="changeDeptShow = false" 
			@refresh="refreshCurUser" v-if="user"></ChangeDept>
	</view>
</template>

<script>
import * as userApi from '@/api/user';
import * as HomeApi from '@/api/home';
import * as WorkApi from '@/api/work/worksubmit';
import * as workorderApi from '@/api/order/workorder';
import Navbar from '@/components/navbar/Navbar';
import Gap from '@/components/gap/Gap';
import ChangeDept from '@/components/definedialog/changeDept';
import storage from '@/utils/storage';
// import myTable from './myTable/index.vue';

export default {
  components: {
    Gap,
    Navbar,
    ChangeDept,
	// myTable,
  },
  data () {
    return {
		// 滚动的表格
		scrollHeight: 200,
		listAr: [],
		tableRowH: [],
		scrollTop: 0, //判断滚动所用为防止滚动到底部多次赋值
		touchstartType: false,
		
		
	  taskTotal: {
		  totalUnFinishedNum: 0,
		  totalFinishedNum: 0,
	  },
	  user: {
		  teamName: '',
	  },
	  changeDeptShow: false,
      activeKey: 'work',
      todo: {
        notice: 0,
        task: 5,
        error: 1
      },
	  annotationAuth: false,
	  waitingHandleList: [
		  {
			  name: 'car',
			  title: '发货',
			  // path: '/pages/work/order/table',
			  path: null,
			  isOpen: false,
		  },
		  {
			  name: 'car',
			  title: '收货',
			  // path: '/pages/work/order/receive',
			  path: null,
		  },
	   ],
	  stockList: [
		   {
			  name: 'hourglass',
			  title: '工单入库',
			  path: '/pages/work/order/instockList?orderType=10',
		   },
		   // {
			  // name: 'home',
			  // title: '总部入库',
			  // path: '/pages/work/dayreport/dutysubmitList',
		   // },
	   ],
	   materialList: [
		  {
			  name: 'shopping-cart',
			  title: '领料',
			  path: '/pages/work/order/picking?orderType=1',
			  //isOpen: true,
		  },
		   {
			  name: 'hourglass',
			  title: '补料',
			  path: '/pages/work/order/picking?orderType=6',
		   },
		   {
			  name: 'star',
			  title: '退料',
			  path: '/pages/work/order/picking?orderType=7',
		   },
	   ],
	   submitReportList: [
		  {
			  name: 'clock',
			  title: '生产报工',
			  path: '/pages/work/dayreport/worksubmit',
			  pathA: '/pages/work/dayreport/worksubmit',
			  pathB: '/pages/work/dayreport/worksubmitViewB',
			  business: 'WORK_SUBMIT',
			  isAB: true,
			  // isOpen: true,
			  badge: true,
			  submitTodo: {
				notice: 0,
				task: 5,
				error: 1
			  },
		   },
		   {
			  name: 'volume',
			  title: '出勤填报',
			  path: '/pages/work/dayreport/dutysubmitList',
			  // isOpen: true,
			  badge: false,
		   },
		   {
			  name: 'home',
			  title: '总部灭菌',
			  // path: '/pages/work/order/receive',
			  path: null,
			  close: true,
		   },
		   {
			  name: 'more-circle',
			  title: '报工报表',
			  path: '/pages/work/dayreport/worksubmitReport',
			  //isOpen: true,
		   },
	   ],
    }
  },
  onShow() {
	// this.loadUserFromCache();
	this.initFeishuSdk();
  },
  onLoad (params) {
	// this.loadUser();
  },
  created () {
	  // this.loadUser();
	  // this.queryAnnotations();
  },
	// watch: {
	// 	listAr() {
	// 		this.init();
	// 	}
	// },
	beforeDestroy() {
		this.clear();
	},
  // 页面加载完成之后执行后置方法
  mounted() {
	  // let sdk = storage.get('FeishuSDK');
	  // if (sdk && sdk === "SUCCESS") {
		 //  // this.$refs.uToast.success(`飞书SDK配置加载成功`);
	  // } else {
		 //  this.$refs.uToast.error(`飞书SDK配置加载失败，请确认是否在飞书APP环境中`);
	  // }
	  // console.log(`vm.$store.state`, this.$store.state.extdata);
	  // this.init();
  },
  methods: {
	  // 滚动表格数据远程加载
	  queryAnnotations() {
		  let param = {
		  	pageNum: 1,
			pageSize: 100,
			verificationStatus: 1
		  };
		  HomeApi.queryAnnotationList(param).then(res => {
		  	if (res.data) {
				this.listAr = res.data || [];
		  	}
			this.init();
		  }).catch(err => {
		  	// 提交异常
		  	console.error("查询批注信息总览发生异常", err);
		  });
	  },
	  // 滚动表格 -- 开始
	  init() {
	  	this.clear();
	  	this.scrollTop = 0;
	  	this.touchstartType = false;
	  	const getBodyHeight = () => {
	  		return new Promise((resolve) => {
	  			const query = uni.createSelectorQuery().in(this);
	  			query.selectAll('.item').boundingClientRect(data => {
	  				resolve(data.map(d => d.height))
	  			}).exec();
	  		});
	  	}
	  
	  	const getHeadHeight = () => {
	  		return new Promise((resolve) => {
	  			const query = uni.createSelectorQuery().in(this);
	  			query.select('.tableTh').boundingClientRect(data => {
	  				resolve(data.height)
	  			}).exec();
	  		})
	  	}
	  
	  	setTimeout(async () => {
	  
	  		this.tableRowH = await getBodyHeight();
	  		const head = await getHeadHeight();
	  
	  		let countH = this.tableRowH.reduce((a, b) => a + b, 0) + head + 20;
	  		console.log(countH)
	  
	  		if (countH > this.scrollHeight) {
	  			this.setTimer()
	  		}
	  	}, 2000)
	  },
	  clear() {
	  	if (this.timer) {
	  		clearInterval(this.timer);
	  		this.timer = null;
	  	}
	  },
	  touchstart() {
	  	this.touchstartType = true
	  },
	  touchend() {
	  	this.touchstartType = false
	  },
	  // 这里设置滚动速度时间越短滚动则越快
	  setTimer() {
	  	this.timer = setInterval(() => {
	  		if (this.touchstartType) return;
	  		if (this.scrollTop > this.tableRowH[0]) {
	  			this.scrollTop = 0
	  			let item = this.listAr.splice(0, 1);
	  			this.listAr.push(item[0])
	  
	  			let tableRowH = this.tableRowH.splice(0, 1);
	  			this.tableRowH.push(tableRowH[0])
	  		}
	  		this.scrollTop++
	  	}, 2000 / 24)
	  },
	  // 滚动表格 -- 结束
	  
	pageDisplayToLoad() {
		this.loadUser();
		this.initTotal();
		this.queryTotalNumber();
	},
	queryTotalNumber() {
		let param = {
			queryKey: this.queryKey,
		};
		workorderApi.queryTotalNumber(param).then(res => {
			if (res.data) {
				this.taskTotal = res.data || {totalUnFinishedNum: 0,totalFinishedNum: 0};
			}
		}).catch(err => {
			// 提交异常
			console.error("查询统计数据发生异常", err);
		});
	},
	remainToFinished() {
		this.navigateTo('/pages/work/tasklist/task');
	},
	loadUserFromCache() {
		this.$store.dispatch('Info').then(res => {
			console.log("刷新获取最新用户:", res);
			this.user = res;
			if (this.user && !this.user.deptId) {
				this.changeDeptShow = true;
				return;
			}
		});
	},
	loadUser() {
		this.$store.dispatch('InfoRefresh').then(res => {
			console.log("刷新获取最新用户:", res);
			this.user = res;
			if (this.user && !this.user.deptId) {
				this.changeDeptShow = true;
				return;
			}
			// 初始化权限
			this.authEffect();
			// 开始初始化数据
			if (this.annotationAuth) {
				this.queryAnnotations();
			}
		});
	},
	authEffect() {
		if (this.user.at) {
			this.annotationAuth = this.user.at.whiteMap && (this.user.at.whiteMap[this.user.teamId] || this.user.at.whiteMap[-1]);
			console.log("白名单权限:", this.annotationAuth);
			
			// 批注权限
			if (!this.annotationAuth) {
				const menus = this.user.at.menus || [];
				this.annotationAuth = menus.indexOf("批注告警") !== -1;
				console.log("菜单权限:", this.annotationAuth);
			}
		}
	},
	refreshCurUser(res) {
		console.log("分厂保存回调:", res);
		if (!res) {
			return;
		}
		this.user = res;
		if (this.user && !this.user.deptId) {
			this.changeDeptShow = true;
			return;
		}
	},
	initTotal() {
		HomeApi.getWorkOrderTotal().then(res => {
			console.log("查询待报工的订单数成功:", res);
			if(res && res.data) {
				this.submitReportList[0].submitTodo.notice = res.data.total || 0;
			}
		}).catch(err => {
			console.error("查询待报工的订单数异常:", err);
		});
	},
	gridClick(item) {
		console.log('this.user:', this.user);
		if (this.user && !this.user.deptId) {
			this.changeDeptShow = true;
			return;
		}
		if (!this.user.at) {
			this.$refs.uToast.success(`4${item.title}｜功能权限需要开通`);
			return;
		}
		if (this.user.at) {
			// console.log("whiteMap:", this.user.at.whiteMap, this.user.at.whiteMap[this.user.teamId]);
			if (this.user.at.whiteMap && (this.user.at.whiteMap[this.user.teamId] || this.user.at.whiteMap[-1])) {
			} else {
				// 非白名单才会校验班组权限
				const teamIds = this.user.at.teamIds || [];
				console.log('this.user.at:', this.user, teamIds.indexOf(this.user.teamId));
				if (teamIds.indexOf(this.user.teamId) === -1) {
					this.$refs.uToast.success(`0${item.title}｜功能权限需要开通`);
					return;
				}
				const menus = this.user.at.menus || [];
				if (menus.length === 0) {
					this.$refs.uToast.success(`1${item.title}｜功能权限需要开通`);
					return;
				}
				if (menus.indexOf(item.title) === -1) {
					this.$refs.uToast.success(`2${item.title}｜功能权限需要开通`);
					return;
				}
			}
		}
		if (item.isAB) {
			WorkApi.getUserView({business: item.business}).then(res => {
				if(res && res.data) {
					if (res.data.uesView === 'A') {
						this.navigateTo(item.pathA);
					} else {
						this.navigateTo(item.pathB);
					}
				} else {
					this.navigateTo(item.pathB);
				}
			}).catch(err => {
				console.error("查询报工AB测试页面出错:", err);
				if (item.pathB) {
					this.navigateTo(item.pathB);
				}
			});
			return;
		}
		// if (item.close) {
		// 	this.$refs.uToast.success(`5${item.title}｜功能还在发布中`);
		// 	return;
		// }
		if (item.path) {
			this.navigateTo(item.path);
			return;
		}
		this.$refs.uToast.success(`7${item.title}｜功能权限需要开通`);
	},
    navigateTo (url) {
      uni.navigateTo({ url: url })
    },
	
	// 飞书授权 <----start
	loadExternalScript(url) { // 这个到template.h5.html动态打包引入
		const script = document.createElement('script');
	    script.src = url;
	    script.onload = () => {
			console.log('SDK JS loaded successfully');
			// SDK 加载完成后可以初始化或使用
			if (window.Lark) {
				// 例如初始化 SDK
				window.Lark.init({
				// 配置参数
				});
			}
			this.initFeishuSdk();
	    };
	    script.onerror = (error) => {
			console.error('Error loading SDK:', error);
	    };
	    document.head.appendChild(script);
	},
	
	initFeishuSdk() {
		if (!window.h5sdk) {
			alert("请在飞书中打开该应用");
			return;
		}
		console.log("App.vue初始化方法");
		this.$store.dispatch('Info')
		.then((result) => {
			console.log("通过toekn获取APS系统用户信息", result);
			// if (!result) {
				this.$store.dispatch('FeishuInfo', {url: location.href.split("#")[0]})
				.then((result) => {
					console.log("飞书配置信息结果", result);
					this.feishuSetting(result.data || {});
				}).catch(err => {
					// TODO
					console.log("飞书配置信息发生异常", err);
				}).finally(() => {
					// TODO
				});
			// }
		}).catch(err => {
			// TODO
			console.log("通过toekn获取APS系统用户信息发生异常", err);
		});
	},
	feishuSetting(data) {
		let { appId, noncestr, signature, timestamp } = data;
	
		try {
			let _this = this;
			window.h5sdk.error((err) => {
				console.log("sdk异常");
				throw ("h5sdk error:", JSON.stringify(err));
			});
	
			window.h5sdk.config({
				appId: appId,
				timestamp: timestamp,
				nonceStr: noncestr,
				signature: signature,
				jsApiList: ["scanCode"],
				//鉴权成功回调
				onSuccess: (res) => {
				  console.log("SDK鉴权成功");
				  console.log(`config success: ${JSON.stringify(res)}`);
				},
				//鉴权失败回调
				onFail: (err) => {
				  console.log("SDK鉴权报错");
				  throw `config failed: ${JSON.stringify(err)}`;
				},
			  });
			  window.h5sdk.ready(() => {
				tt.requestAuthCode({
					appId: appId,
					success: async (info) => {
					  console.log("获取code成功:", info);
					  _this.$store.dispatch('ApsLogin', { code: info.code})
						.then((result) => {
							// uni.$u.toast('飞书鉴权成功');
							console.log("通过code登录APS系统用户信息", result);
							_this.pageDisplayToLoad();
						}).catch(err => {
							uni.$u.toast(`飞书鉴权失败:${err.message}`);
							console.log("通过code登录APS系统用户信息发生异常", err);
						}).finally(() => {
							// TODO
						});
					},
					fail: (error) => {
					  console.error("获取code失败！", error);
					},
				});
			});
		} catch(e){
			//TODO handle the exception
			uni.$u.toast(`FeishuSDK异常:${e.message}`);
			console.error("加载 FeishuSDK 发生异常", e);
		}
	},
	// 飞书配置加载 end---->
	
  }
}
</script>

<style lang="scss">
	
.item-tj {
  width: 100%;
  height: 160rpx;
  border-radius: 28rpx;
  
  &-frist {
    background-color: rgba($color: #2979ff, $alpha: 0.8);
    // background-image: url('/static/img/bg/qb.png');
  }

  &-second {
    background-color: rgba($color: #19be6b, $alpha: 0.8);
    // background-image: url('/static/img/bg/qb.png');
  }

  &-thrid {
    background-color: rgba($color: #303133, $alpha: 0.8);
    // background-image: url('/static/img/bg/qb.png');
  }
}
.grid-text {
	font-size: 16px;
	// color: #909399;
	padding: 10rpx 0 20rpx 0rpx;
	/* #ifndef APP-PLUS */
	box-sizing: border-box;
	/* #endif */
}

.pull-text {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  font-size: 16px;
  color: #999;
}
.content {
  padding: 20px;
}
</style>